<template>
    <div class="publish-page">
        <!-- 导航栏 -->
        <van-nav-bar title="Create Post" left-text="Cancel" left-arrow @click-left="handleCancel">
            <template #right>
                <van-button size="small" type="primary" :disabled="!canPublish" :loading="publishing"
                    @click="handlePublish">
                    Publish
                </van-button>
            </template>
        </van-nav-bar>

        <div class="publish-content">
            <!-- 内容类型选择 -->
            <div class="content-type-section">
                <h3>What would you like to share?</h3>
                <div class="type-options">
                    <div v-for="type in contentTypes" :key="type.value" class="type-option"
                        :class="{ active: selectedType === type.value }" @click="selectContentType(type.value)">
                        <van-icon :name="type.icon" size="24" />
                        <div class="type-info">
                            <div class="type-title">{{ type.title }}</div>
                            <div class="type-description">{{ type.description }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 内容编辑区域 -->
            <div class="content-editor">
                <!-- 标题输入 -->
                <van-field v-model="postData.title" placeholder="Give your post a title..." maxlength="100"
                    show-word-limit class="title-input" />

                <!-- 内容输入 -->
                <van-field v-model="postData.content" type="textarea"
                    placeholder="Share your thoughts, experience, or ask for help..." rows="6" autosize maxlength="2000"
                    show-word-limit class="content-input" />

                <!-- 训练结果选择 (仅限经验分享) -->
                <div class="training-result-section"
                    v-if="selectedType === 'experience' && recentTrainingResults.length > 0">
                    <h4>Attach Training Result (Optional)</h4>
                    <div class="training-results">
                        <div v-for="result in recentTrainingResults" :key="result.id" class="training-result-item"
                            :class="{ selected: postData.trainingResultId === result.id }"
                            @click="toggleTrainingResult(result.id)">
                            <div class="result-info">
                                <div class="result-title">{{ result.scenarioTitle }}</div>
                                <div class="result-meta">
                                    <span>Score: {{ result.score }}/100</span>
                                    <span>•</span>
                                    <span>{{ formatTime(result.completedAt) }}</span>
                                </div>
                            </div>
                            <van-icon :name="postData.trainingResultId === result.id ? 'success' : 'plus'"
                                :color="postData.trainingResultId === result.id ? '#07c160' : '#969799'" />
                        </div>
                    </div>
                </div>

                <!-- 图片上传 -->
                <div class="image-upload-section">
                    <h4>Images (Optional)</h4>
                    <ImageUpload v-model="postData.images" :max-count="9" @upload="handleImageUpload" />
                </div>

                <!-- 标签选择 -->
                <div class="tags-section">
                    <TagSelector v-model="postData.tags" :content-text="postData.content" :max-tags="10" />
                </div>

                <!-- 发布设置 -->
                <div class="publish-settings">
                    <h4>Publish Settings</h4>

                    <van-cell-group>
                        <van-cell title="Visibility">
                            <template #value>
                                <van-radio-group v-model="postData.visibility">
                                    <van-radio name="public">Public</van-radio>
                                    <van-radio name="followers">Followers Only</van-radio>
                                </van-radio-group>
                            </template>
                        </van-cell>

                        <van-cell title="Allow Comments">
                            <template #value>
                                <van-switch v-model="postData.allowComments" />
                            </template>
                        </van-cell>

                        <van-cell title="Enable Notifications" v-if="selectedType === 'help'">
                            <template #value>
                                <van-switch v-model="postData.enableNotifications" />
                            </template>
                        </van-cell>
                    </van-cell-group>

                    <!-- 悬赏设置 (仅限求助) -->
                    <div class="reward-section" v-if="selectedType === 'help'">
                        <van-cell title="Offer Reward Points">
                            <template #value>
                                <van-switch v-model="postData.hasReward" />
                            </template>
                        </van-cell>

                        <van-field v-if="postData.hasReward" v-model="postData.rewardPoints" type="number"
                            label="Reward Points" placeholder="Enter points to offer" :min="10" :max="1000" />
                    </div>
                </div>
            </div>
        </div>

        <!-- 发布确认弹窗 -->
        <van-popup v-model:show="showConfirmPopup" position="center" round>
            <div class="confirm-popup">
                <div class="popup-header">
                    <h3>Ready to Publish?</h3>
                </div>
                <div class="popup-content">
                    <div class="post-preview">
                        <div class="preview-type">
                            <van-icon :name="getTypeIcon(selectedType)" />
                            <span>{{ getTypeTitle(selectedType) }}</span>
                        </div>
                        <div class="preview-title">{{ postData.title }}</div>
                        <div class="preview-content">{{ postData.content.substring(0, 100) }}...</div>
                        <div class="preview-meta">
                            <span>{{ postData.images.length }} images</span>
                            <span>•</span>
                            <span>{{ postData.tags.length }} tags</span>
                            <span>•</span>
                            <span>{{ postData.visibility }}</span>
                        </div>
                    </div>
                </div>
                <div class="popup-actions">
                    <van-button block @click="showConfirmPopup = false">Review</van-button>
                    <van-button type="primary" block @click="confirmPublish">Publish Now</van-button>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { communityApi } from '@/api'
import ImageUpload from '@/components/ImageUpload.vue'
import TagSelector from '@/components/TagSelector.vue'

const router = useRouter()

// 响应式数据
const publishing = ref(false)
const showConfirmPopup = ref(false)
const selectedType = ref('experience')

const postData = ref({
    title: '',
    content: '',
    images: [] as any[],
    tags: [] as string[],
    visibility: 'public',
    allowComments: true,
    enableNotifications: true,
    hasReward: false,
    rewardPoints: 50,
    trainingResultId: null as number | null
})

// 内容类型选项
const contentTypes = [
    {
        value: 'experience',
        title: 'Share Experience',
        description: 'Share your training results or social experiences',
        icon: 'medal-o'
    },
    {
        value: 'tips',
        title: 'Tips & Advice',
        description: 'Share helpful tips and advice with the community',
        icon: 'bulb-o'
    },
    {
        value: 'help',
        title: 'Ask for Help',
        description: 'Ask the community for advice or support',
        icon: 'question-o'
    },
    {
        value: 'discussion',
        title: 'Start Discussion',
        description: 'Start a general discussion or conversation',
        icon: 'chat-o'
    }
]

// 模拟最近的训练结果
const recentTrainingResults = ref([
    {
        id: 1,
        scenarioTitle: 'Coffee Shop Conversation',
        score: 85,
        completedAt: new Date().toISOString()
    },
    {
        id: 2,
        scenarioTitle: 'Job Interview Practice',
        score: 92,
        completedAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
    },
    {
        id: 3,
        scenarioTitle: 'Team Meeting Discussion',
        score: 78,
        completedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
    }
])

// 计算属性
const canPublish = computed(() => {
    return postData.value.title.trim().length > 0 &&
        postData.value.content.trim().length > 10
})

// 方法
const selectContentType = (type: string) => {
    selectedType.value = type

    // 根据类型调整默认设置
    if (type === 'help') {
        postData.value.enableNotifications = true
    }
}

const toggleTrainingResult = (resultId: number) => {
    if (postData.value.trainingResultId === resultId) {
        postData.value.trainingResultId = null
    } else {
        postData.value.trainingResultId = resultId
    }
}

const handleImageUpload = () => {
    // 图片上传处理逻辑已在 ImageUpload 组件中处理
}

const handleCancel = async () => {
    if (hasUnsavedChanges()) {
        try {
            await showConfirmDialog({
                title: 'Discard Changes',
                message: 'You have unsaved changes. Are you sure you want to leave?'
            })
            router.back()
        } catch {
            // 用户取消
        }
    } else {
        router.back()
    }
}

const hasUnsavedChanges = () => {
    return postData.value.title.trim().length > 0 ||
        postData.value.content.trim().length > 0 ||
        postData.value.images.length > 0 ||
        postData.value.tags.length > 0
}

const handlePublish = () => {
    showConfirmPopup.value = true
}

const confirmPublish = async () => {
    try {
        publishing.value = true
        showConfirmPopup.value = false

        // 构建发布数据
        const getShareType = (type: string): "experience" | "achievement" | "question" => {
            switch (type) {
                case 'experience':
                    return 'experience'
                case 'tips':
                    return 'experience' // Tips can be treated as experience sharing
                case 'help':
                    return 'question'
                case 'discussion':
                    return 'question' // Discussion can be treated as question
                default:
                    return 'experience'
            }
        }

        const publishData = {
            title: postData.value.title.trim(),
            content: postData.value.content.trim(),
            share_type: getShareType(selectedType.value),
            tags: postData.value.tags,
            images: postData.value.images,
            is_public: postData.value.visibility === 'public',
            allow_comments: postData.value.allowComments,
            training_result_id: postData.value.trainingResultId,
            reward_points: postData.value.hasReward ? postData.value.rewardPoints : undefined
        }

        // 发布内容
        if (selectedType.value === 'help') {
            await communityApi.createHelpRequest({
                title: publishData.title,
                description: publishData.content,
                category: 'other'
            })
        } else {
            await communityApi.createShare(publishData)
        }

        showToast('Published successfully!')
        router.push('/community')
    } catch (error) {
        console.error('Failed to publish:', error)
        showToast('Failed to publish')
    } finally {
        publishing.value = false
    }
}

const getTypeIcon = (type: string) => {
    const typeMap: Record<string, string> = {
        'experience': 'medal-o',
        'tips': 'bulb-o',
        'help': 'question-o',
        'discussion': 'chat-o'
    }
    return typeMap[type] || 'chat-o'
}

const getTypeTitle = (type: string) => {
    const typeMap: Record<string, string> = {
        'experience': 'Experience Sharing',
        'tips': 'Tips & Advice',
        'help': 'Help Request',
        'discussion': 'Discussion'
    }
    return typeMap[type] || 'Post'
}

const formatTime = (timestamp: string) => {
    const now = new Date()
    const time = new Date(timestamp)
    const diff = now.getTime() - time.getTime()

    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (hours < 24) {
        return `${hours}h ago`
    } else {
        return `${days}d ago`
    }
}

// 生命周期
onMounted(() => {
    // 可以在这里加载用户的草稿或其他初始数据
})
</script>

<style lang="scss" scoped>
.publish-page {
    min-height: 100vh;
    background: #f7f8fa;

    .publish-content {
        padding: 16px;

        .content-type-section {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;

            h3 {
                font-size: 18px;
                color: #323233;
                margin: 0 0 16px 0;
                font-weight: 600;
            }

            .type-options {
                display: flex;
                flex-direction: column;
                gap: 12px;

                .type-option {
                    display: flex;
                    gap: 16px;
                    padding: 16px;
                    border: 2px solid #ebedf0;
                    border-radius: 12px;
                    cursor: pointer;
                    transition: all 0.3s;

                    &:hover {
                        border-color: #1989fa;
                    }

                    &.active {
                        border-color: #1989fa;
                        background: #f0f8ff;

                        .van-icon {
                            color: #1989fa;
                        }
                    }

                    .van-icon {
                        color: #646566;
                        margin-top: 2px;
                        flex-shrink: 0;
                    }

                    .type-info {
                        flex: 1;

                        .type-title {
                            font-size: 16px;
                            color: #323233;
                            font-weight: 500;
                            margin-bottom: 4px;
                        }

                        .type-description {
                            font-size: 14px;
                            color: #646566;
                            line-height: 1.4;
                        }
                    }
                }
            }
        }

        .content-editor {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;

            .title-input,
            .content-input {
                margin-bottom: 20px;

                :deep(.van-field__control) {
                    font-size: 16px;
                    line-height: 1.5;
                }
            }

            .title-input {
                :deep(.van-field__control) {
                    font-weight: 600;
                    font-size: 18px;
                }
            }

            .training-result-section {
                margin-bottom: 20px;

                h4 {
                    font-size: 16px;
                    color: #323233;
                    margin: 0 0 12px 0;
                    font-weight: 500;
                }

                .training-results {
                    display: flex;
                    flex-direction: column;
                    gap: 8px;

                    .training-result-item {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 12px;
                        border: 1px solid #ebedf0;
                        border-radius: 8px;
                        cursor: pointer;
                        transition: all 0.3s;

                        &:hover {
                            border-color: #1989fa;
                        }

                        &.selected {
                            border-color: #07c160;
                            background: #f0f9f0;
                        }

                        .result-info {
                            flex: 1;

                            .result-title {
                                font-size: 15px;
                                color: #323233;
                                font-weight: 500;
                                margin-bottom: 4px;
                            }

                            .result-meta {
                                font-size: 12px;
                                color: #969799;

                                span {
                                    margin-right: 4px;
                                }
                            }
                        }
                    }
                }
            }

            .image-upload-section,
            .tags-section {
                margin-bottom: 20px;

                h4 {
                    font-size: 16px;
                    color: #323233;
                    margin: 0 0 12px 0;
                    font-weight: 500;
                }
            }

            .publish-settings {
                h4 {
                    font-size: 16px;
                    color: #323233;
                    margin: 0 0 12px 0;
                    font-weight: 500;
                }

                .van-cell-group {
                    border-radius: 8px;
                    overflow: hidden;
                }

                .reward-section {
                    margin-top: 12px;

                    .van-cell-group {
                        border-radius: 8px;
                        overflow: hidden;
                    }
                }
            }
        }
    }
}

.confirm-popup {
    padding: 24px;
    width: 320px;

    .popup-header {
        text-align: center;
        margin-bottom: 20px;

        h3 {
            font-size: 18px;
            color: #323233;
            margin: 0;
            font-weight: 600;
        }
    }

    .popup-content {
        margin-bottom: 20px;

        .post-preview {
            background: #f7f8fa;
            border-radius: 8px;
            padding: 16px;

            .preview-type {
                display: flex;
                align-items: center;
                gap: 8px;
                margin-bottom: 8px;
                font-size: 14px;
                color: #1989fa;
                font-weight: 500;
            }

            .preview-title {
                font-size: 16px;
                color: #323233;
                font-weight: 600;
                margin-bottom: 8px;
            }

            .preview-content {
                font-size: 14px;
                color: #646566;
                line-height: 1.5;
                margin-bottom: 12px;
            }

            .preview-meta {
                font-size: 12px;
                color: #969799;

                span {
                    margin-right: 4px;
                }
            }
        }
    }

    .popup-actions {
        display: flex;
        gap: 12px;
    }
}
</style>